package com.hs.server.thirdPart.hs;

import com.alibaba.fastjson.JSON;
import com.hs.server.domain.ShDetItemConfig;
import com.hs.server.domain.VehQueuexxb;
import com.hs.server.domain.VehZnshinfo;
import com.hs.server.domain.VehZnshzlzpxx;
import com.hs.server.dto.VehPhotodesDto;
import com.hs.server.dto.Vehicle;
import com.hs.server.mapper.XbjcMapper;
import com.hs.server.service.*;
import com.hs.server.thirdPart.IOpenService;
import com.hs.server.thirdPart.hs.params.IQ_18C22;
import com.hs.server.utils.MD5Encryption;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 东莞预审核
 * @Author: sujianzhi
 * @Date: 2021/4/19 11:23
 */
@Slf4j
@Service
@ConditionalOnProperty(name = "thirdpart.name", havingValue = "hs")
public class HSOpenServiceImpl implements IOpenService {

    @Autowired
    private XbjcMapper xbjcMapper;
    @Autowired
    private VehZnshinfoService vehZnshinfoService;
    @Autowired
    private VehZnshzlzpxxService vehZnshzlzpxxService;
    @Autowired
    private ShDetItemConfigService shDetItemConfigService;
    @Autowired
    private VehQueuexxbService vehQueuexxbService;
    @Autowired
    private ShItemConfigService shItemConfigService;

    private String jyjgbh;

    // 定义常量
    private static final String SHZT_INITIAL = "0"; // 审核状态：初始
    private static final String CZZT_UNINSPECTED = "0"; // 操作状态：未检验
    private static final String SHLB_INSPECTION = "2"; // 审核类别 	0：查验；1：检验;  2:预审核
    private static final String YCZT_NORMAL = "0"; //审核是否异常（图片访问不了导致审核失败）0:正常；1:异常
    private static final String SHZT_NO_NEED_AUDIT = "3"; // 审核状态：无需审核
    private static final String SHZT_NEED_AUDIT = "4"; // 审核状态：正在审核

    private static final String SHZT_PASS_AUDIT = "1"; // 审核状态：通过

    @PostConstruct
    public void init() {
        this.jyjgbh = xbjcMapper.getJyjgbh();
    }

    @Override
    public List<Vehicle> IQ_18C22_1(IQ_18C22 f, String shlb) {
        if (f == null || StringUtils.isEmpty(f.getQsrq()) || StringUtils.isEmpty(f.getFhzdjls())) {
            log.warn("IQ_18C22_1: 查询参数缺失。");
            return new ArrayList<>();
        }
        try {
            return xbjcMapper.getVehicleList(f.getQsrq(), Integer.parseInt(f.getFhzdjls()));
        } catch (NumberFormatException e) {
            log.error("IQ_18C22_1: 转换返回最大记录数失败，参数：{}", f.getFhzdjls(), e);
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("IQ_18C22_1: 查询待审核流水信息异常", e);
            return new ArrayList<>();
        }
    }

    @Override
    public void IQ_18C22_2(IQ_18C22 iq_18C22) {
        long startTime = System.currentTimeMillis();
        String jylsh = iq_18C22.getLsh();

        if (StringUtils.isEmpty(jylsh)) {
            log.warn("IQ_18C22_2: 流水号为空，无法处理。");
            return;
        }

        try {
            VehZnshinfo vehZnshinfo = vehZnshinfoService.GetVehZnshinfoByLsh(jylsh);
            boolean isFirstAcquisition = (vehZnshinfo == null);

            if (isFirstAcquisition) {
                vehZnshinfo = initializeVehZnshinfo(iq_18C22, jylsh);
                if (vehZnshinfo == null) {
                    return; // 初始化失败，已记录日志并返回
                }
            } else {
                resetAndSaveVehZnshinfo(vehZnshinfo);
            }

            List<VehZnshzlzpxx> photoList = processPhotos(jylsh, vehZnshinfo.getHphm());
            if (CollectionUtils.isEmpty(photoList)) {
                log.info("IQ_18C22_2: 车牌号【{}】无照片返回!!", vehZnshinfo.getHphm());
                xbjcMapper.updateVehFlowYshbj(jylsh, SHZT_NO_NEED_AUDIT);
                return;
            }

            ShDetItemConfig shDetItemConfig = shDetItemConfigService.getDetItemConfig(
                    vehZnshinfo.getCllx(), vehZnshinfo.getSyxz(), SHLB_INSPECTION);

            if (shDetItemConfig == null) {
                log.warn("IQ_18C22_2: 暂无该车辆类型为{}，使用性质为{}的配置(shDetItemConfig)，【车牌号】{}",
                        vehZnshinfo.getCllx(), vehZnshinfo.getSyxz(), vehZnshinfo.getHphm());
                xbjcMapper.updateZpshbj(jylsh, SHZT_NO_NEED_AUDIT);
                xbjcMapper.updateVehFlowYshbj(jylsh, SHZT_NO_NEED_AUDIT);
                return;
            }

            createQueue(vehZnshinfo, shDetItemConfig, photoList);

            long endTime = System.currentTimeMillis();
            log.info("IQ_18C22_2: 【{}】入库完成耗时: {}毫秒", vehZnshinfo.getHphm(), (endTime - startTime));

        } catch (Exception e) {
            log.error("IQ_18C22_2: 处理流水号【{}】时发生异常", jylsh, e);
            // 异常发生时，可能需要回滚或更新状态，具体取决于业务需求
        }
    }

    /**
     * 初始化车辆信息
     * @param iq_18C22
     * @param jylsh
     * @return
     */
    private VehZnshinfo initializeVehZnshinfo(IQ_18C22 iq_18C22, String jylsh) {
        Vehicle vehicle = iq_18C22.getVehicle();
        if (vehicle == null) {
            log.warn("initializeVehZnshinfo: 流水号【{}】的车辆信息为空，无法初始化VehZnshinfo。", jylsh);
            return null;
        }

        VehZnshinfo vehZnshinfo = JSON.parseObject(JSON.toJSONString(vehicle), VehZnshinfo.class);
        if (vehZnshinfo == null) {
            log.error("initializeVehZnshinfo: 流水号【{}】的车辆信息JSON转换失败。", jylsh);
            return null;
        }

        ShDetItemConfig shDetItemConfig = shDetItemConfigService.getDetItemConfig(
                vehZnshinfo.getCllx(), vehZnshinfo.getSyxz(), SHLB_INSPECTION);

        if (shDetItemConfig == null) {
            log.warn("initializeVehZnshinfo: 暂无该车辆类型为{}，使用性质为{}的配置(shDetItemConfig)，【车牌号】{}",
                    vehZnshinfo.getCllx(), vehZnshinfo.getSyxz(), vehZnshinfo.getHphm());
            xbjcMapper.updateZpshbj(jylsh, SHZT_NO_NEED_AUDIT);
            xbjcMapper.updateVehFlowYshbj(jylsh, SHZT_NO_NEED_AUDIT);
            return null;
        }
        vehZnshinfo.setLsh(jylsh);
        vehZnshinfo.setShzt(SHZT_INITIAL);
        vehZnshinfo.setCjsj(new Date());
        vehZnshinfo.setShlb(SHLB_INSPECTION);
        vehZnshinfo.setCzzt(CZZT_UNINSPECTED);
        vehZnshinfo.setYczt(YCZT_NORMAL);
        vehZnshinfo.setSqshsj(new Date());
        vehZnshinfo.setJyjgbh(jyjgbh);

        vehZnshinfo.setPzclfl(shDetItemConfig.getClfl());
        vehZnshinfo.setPzcllx(shDetItemConfig.getCllx());
        vehZnshinfo.setPzsyxz(shDetItemConfig.getSyxz());
        vehZnshinfo.setPzzpzl(shDetItemConfig.getZpzl());
        vehZnshinfo.setPzpzx(shDetItemConfig.getPzx());
        vehZnshinfo.setJyw(MD5Encryption.encryption(vehZnshinfo.toString()));

        vehZnshinfoService.save(vehZnshinfo);
        log.info("initializeVehZnshinfo: {}-->增加车辆信息成功！", vehZnshinfo.getHphm());
        return vehZnshinfo;
    }

    /**
     * 更新车辆信息
     * @param vehZnshinfo
     */
    private void resetAndSaveVehZnshinfo(VehZnshinfo vehZnshinfo) {
        vehZnshinfo.setShzt(SHZT_INITIAL);
        vehZnshinfo.setCzzt(CZZT_UNINSPECTED);
        vehZnshinfo.setCjsj(new Date());
        vehZnshinfo.setGxsj(new Date());
        vehZnshinfo.setSqshsj(new Date());
        vehZnshinfoService.updateVehZnshinfo(vehZnshinfo);
        log.info("resetAndSaveVehZnshinfo: {}-->更新车辆信息成功！", vehZnshinfo.getHphm());
    }

    /**
     * 处理照片信息
     * @param jylsh
     * @param hphm
     * @return
     */
    private List<VehZnshzlzpxx> processPhotos(String jylsh, String hphm) {
        List<VehZnshzlzpxx> processedPhotos = new ArrayList<>();
        List<VehPhotodesDto> photodes = xbjcMapper.getPhotoInfoList(jylsh);

        if (CollectionUtils.isEmpty(photodes)) {
            log.info("processPhotos: 流水号【{}】无照片信息返回。", jylsh);
            return processedPhotos;
        }

        for (VehPhotodesDto photoDto : photodes) {
            VehZnshzlzpxx vehZnshzlzpxx = JSON.parseObject(JSON.toJSONString(photoDto), VehZnshzlzpxx.class);
            if (vehZnshzlzpxx == null) {
                log.warn("processPhotos: 照片信息JSON转换失败，跳过。原始数据: {}", photoDto);
                continue;
            }
            vehZnshzlzpxx.setLsh(jylsh);
            vehZnshzlzpxx.setShzt(SHZT_INITIAL);
            vehZnshzlzpxx.setZpurl(jylsh + "_" + vehZnshzlzpxx.getZpzl() + ".jpg");
            vehZnshzlzpxxService.AddVehZnshzlzpxx(vehZnshzlzpxx);
            processedPhotos.add(vehZnshzlzpxx);
        }
        log.info("processPhotos: 【{}】添加照片信息成功！照片数量：{}", hphm, processedPhotos.size());
        return processedPhotos;
    }

    /**
     * 生成队列信息
     * @param vehZnshinfo
     * @param shDetItemConfig
     * @param currentPhotos
     */
    private void createQueue(VehZnshinfo vehZnshinfo, ShDetItemConfig shDetItemConfig, List<VehZnshzlzpxx> currentPhotos) {
        String jylsh = vehZnshinfo.getLsh();
        //获取当前的照片种类
        List<String> currentPhotoZpzls = currentPhotos.stream()
                .map(VehZnshzlzpxx::getZpzl)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

        //获取配置检验项
        List<String> pzxList = Arrays.stream(shDetItemConfig.getPzx().split(","))
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
        //获取还没有审核的照片
        List<VehZnshzlzpxx> allNotReviewedPhotos = vehZnshzlzpxxService.GetVehZnshzlzpxxListWithNotReviewed(jylsh);


        int shzt0Count = 0;
        for (VehZnshzlzpxx zp : allNotReviewedPhotos) {
            String zpzl = zp.getZpzl();
            // 如果该照片种类无需审核
            if (!shDetItemConfig.getZpzl().contains(zpzl)) {
                if (currentPhotoZpzls.contains(zpzl)) {
                    shzt0Count++;
                }
                // 清空检验项并更新照片审核状态为无需审核
                zp.setJyx("");
                zp.setShzt(SHZT_NO_NEED_AUDIT);
                zp.setShzt2(SHZT_NO_NEED_AUDIT);
                vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
                xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_NO_NEED_AUDIT, zpzl);
                log.info("createQueue: 流水号【{}】照片种类【{}】无需审核，已更新状态。", jylsh, zpzl);
                continue;
            }

            //如果号牌种类是51、52的，则环保报告表1，2表不用审核
            if (vehZnshinfo.getHpzl().equals("51") || vehZnshinfo.getHpzl().equals("52")) {//|| vehZnshinfo.getJylb().equals("00") || vehZnshinfo.getRlzl().contains("C")
                if (zpzl.equals("0209") || zpzl.equals("0210")){
                    // 清空检验项并更新照片审核状态为无需审核
                    zp.setJyx("");
                    zp.setShzt(SHZT_NO_NEED_AUDIT);
                    zp.setShzt2(SHZT_NO_NEED_AUDIT);
                    vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
                    xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_NO_NEED_AUDIT, zpzl);
                    log.info("createQueue: 流水号【{}】照片种类【{}】无需审核，已更新状态。(号牌种类是51、52)", jylsh, zpzl);
                    continue;
                }
            }
            //新车不用审核行驶证照片
//            if (vehZnshinfo.getJylb().equals("00")){
//                if (zpzl.equals("0201") || zpzl.equals("0287")){
//                    // 清空检验项并更新照片审核状态为无需审核
//                    zp.setJyx("");
//                    zp.setShzt(SHZT_NO_NEED_AUDIT);
//                    zp.setShzt2(SHZT_NO_NEED_AUDIT);
//                    vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
//                    xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_NO_NEED_AUDIT, zpzl);
//                    log.info("createQueue: 流水号【{}】照片种类【{}】无需审核，已更新状态。(新车行驶证)", jylsh, zpzl);
//                    continue;
//                }
//            }

            // 获取该照片种类需要检测的所有配置项
            List<String> shxList = shItemConfigService.getShxdmList(zpzl);
            if (CollectionUtils.isEmpty(shxList)) {
                log.warn("createQueue: 流水号【{}】照片种类【{}】未找到对应的审核项配置，已更新状态。", jylsh,zpzl);
                xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_NO_NEED_AUDIT, zpzl);
                zp.setJyx("");
                zp.setShzt(SHZT_PASS_AUDIT);
                vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
                continue;
            }

            // 与pzx做交集，结果为该照片只需检验的项
            String jyx = StringUtils.join(CollectionUtils.intersection(pzxList, shxList).toArray(), ",");
            if (StringUtils.isBlank(jyx)){
                log.warn("createQueue: 流水号【{}】照片种类【{}】不存在需检验的项，默认通过，已更新状态。", jylsh,zpzl);
                xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_PASS_AUDIT, zpzl);
                zp.setJyx("");
                zp.setShzt(SHZT_PASS_AUDIT);
                vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
                continue;
            }

            // 写入队列对象存入数据库
            VehQueuexxb vehQueuexxb = new VehQueuexxb();
            vehQueuexxb.setZt(SHZT_INITIAL);
            vehQueuexxb.setLsh(jylsh);
            vehQueuexxb.setCjsj(new Date());
            vehQueuexxb.setZpzl(zpzl);
            vehQueuexxb.setJyx(jyx);
            vehQueuexxbService.addVehQueuexxb(vehQueuexxb);
            log.info("createQueue: 流水号【{}】照片种类【{}】已添加到队列。", jylsh, zpzl);

            // 将检验项写入VehZnshzlzpxx表
            zp.setJyx(jyx);
            vehZnshzlzpxxService.UpdateZnshzlzpxx(zp);
            xbjcMapper.updateZpshbjByZpzl(jylsh, SHZT_NEED_AUDIT,zpzl);
        }

        // 如果本次查询的照片列表中的所有照片都无需审核
        if (shzt0Count > 0 && shzt0Count == currentPhotos.size()) {
            log.info("createQueue: 【第二次获取照片且所有照片都无需审核】流水号：{}", jylsh);
            // todo 此处是同步调用18C92向检验监管系统上报照片检验结果
        }

        xbjcMapper.updateVehFlowYshbj(jylsh, SHZT_NEED_AUDIT);
        log.info("createQueue: 流水号【{}】已更新车辆流程审核标记为需要审核。", jylsh);
    }
}